package com.xoa.service.party;

import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.party.CommunityPatrolMapper;
import com.xoa.model.department.Department;
import com.xoa.model.enclosure.Attachment;
import com.xoa.model.party.CommunityPatrol;
import com.xoa.model.users.Users;
import com.xoa.util.ExcelUtil;
import com.xoa.util.GetAttachmentListUtil;
import com.xoa.util.common.log.FileUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.common.wrapper.BaseWrapper;
import com.xoa.util.page.PageParams;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 程叶同 on 2018/1/5.
 * 空气重污染 社区巡查
 */
@Service
public class CommunityPatrolService {
    @Autowired
    CommunityPatrolMapper communityPatrolMapper;
    
    @Autowired
    DepartmentMapper departmentMapper;

    /**
     * @Author 程叶同
     * @Description
     * @return com.xoa.util.common.wrapper.BaseWrapper
     * @Date 13:46 2018/1/5
     */
    public BaseWrapper addPatrol(HttpServletRequest request, CommunityPatrol communityPatrol){
        BaseWrapper baseWrapper=new BaseWrapper();
        if(communityPatrol!=null){
            int insert = communityPatrolMapper.insert(communityPatrol);
            if(insert>0){
                baseWrapper.setFlag(true);
                baseWrapper.setMsg("添加成功");
            }else{
                baseWrapper.setFlag(false);
                baseWrapper.setMsg("添加失败");
            }
        }else{
            baseWrapper.setFlag(false);
            baseWrapper.setMsg("数据为空");
        }
        return  baseWrapper;
    }

    /**
    * @Author 程叶同
    * @Description 删除
    * @Date 13:54 2018/1/5
    */
    public BaseWrapper deletePatrol(HttpServletRequest request, Integer id){
        BaseWrapper baseWrapper=new BaseWrapper();
        Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class,new Users());
        if(id!=null&&id!=0){
            CommunityPatrol communityPatrol = communityPatrolMapper.selectByPrimaryKey(id);
            if(communityPatrol!=null){
                    communityPatrolMapper.deleteByPrimaryKey(id);
                    baseWrapper.setFlag(true);
                    baseWrapper.setMsg("删除成功");
            }

        }
        return baseWrapper;
    }


    /**
    * @Author 程叶同
    * @Description 查询所有记录
    * @Date 15:13 2018/1/5
    */

    public BaseWrapper getPatrolInfo(HttpServletRequest request, Integer page, Integer size, String subcounty, String processResult){
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class,new Users());
        BaseWrapper baseWrapper=new BaseWrapper();
        List<CommunityPatrol> results=new ArrayList<CommunityPatrol>();
        Map<String,Object> map=new HashMap<String,Object>();
        Map<String,Object> map1=new HashMap<String,Object>();
        map.put("processResult",processResult);
        map1.put("processResult",processResult);
        PageParams pageParams=new PageParams();
        pageParams.setUseFlag(true);
        pageParams.setPage(page);
        pageParams.setPageSize(size);
        map.put("page",page-1);
        map.put("pageParams",pageParams);
        int total=0;
        //获取所属部门
        Department department=departmentMapper.getDeptById(user.getDeptId());
        if(department.getDeptParent()==27){
            //属于社区
            map.put("subcounty",subcounty);
            map1.put("subcounty",subcounty);
            results=communityPatrolMapper.selectList(map);
            total = communityPatrolMapper.totalItems(map1);

        }else{
            results=communityPatrolMapper.selectList(map);
            total = communityPatrolMapper.totalItems(map1);

        }
        if(results!=null){
            baseWrapper.setFlag(true);
            baseWrapper.setData(results);
            baseWrapper.setMsg("ok");
        }else{
            baseWrapper.setMsg("error");
            baseWrapper.setFlag(false);
        }

        return  baseWrapper;
    }
    /**
    * @Author 程叶同
    * @Description 更新数据
    * @Date 10:04 2018/1/6
    */
    public BaseWrapper updateData(HttpServletRequest request, CommunityPatrol communityPatrol){
        BaseWrapper baseWrapper=new BaseWrapper();
        Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class,new Users());
        if(communityPatrol!=null){
                int i = communityPatrolMapper.updateByPrimaryKey(communityPatrol);
                if(i>0){
                    baseWrapper.setMsg("修改成功");
                    baseWrapper.setFlag(true);
                }
        }
        return  baseWrapper;
    }
    /**
    * @Author 程叶同
    * @Description 查看详情
    * @Date 10:05 2018/1/6
    */
    public BaseWrapper getDetails(HttpServletRequest request, Integer id){
        BaseWrapper baseWrapper=new BaseWrapper();
        String sqlType = "xoa"
                + (String) request.getSession().getAttribute("loginDateSouse");
        if(id!=null){
            CommunityPatrol communityPatrol = communityPatrolMapper.selectByPrimaryKey(id);
            List<Attachment> attachments = GetAttachmentListUtil.returnAttachment(communityPatrol.getAttachmentName(), communityPatrol.getAttachmentId(), sqlType, GetAttachmentListUtil.MODULE_parameter);
            communityPatrol.setAttachmentList(attachments);
            if(communityPatrol!=null){
                baseWrapper.setMsg("查询成功");
                baseWrapper.setData(communityPatrol);
                baseWrapper.setFlag(true);
            }else{
                baseWrapper.setMsg("没有查到数据");
                baseWrapper.setFlag(false);
            }
        }else{
            baseWrapper.setMsg("参数错误");
            baseWrapper.setFlag(false);
        }
        return  baseWrapper;
    }
    /**
    * @Author 程叶同
    * @Description  文件导出
    * @Date 13:53 2018/1/8
    */
    public BaseWrapper fileOut(HttpServletRequest request, HttpServletResponse response, String ids){
        BaseWrapper baseWrapper=new BaseWrapper();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<CommunityPatrol> communityPatrols=null;
        if(ids!=null&&ids!=""){
            String[] id=ids.split(",");
            Map<String,Object> map=new HashMap<String,Object>();
            map.put("id",id);
            communityPatrols=communityPatrolMapper.selectList(map);
        }
        if(communityPatrols!=null){
            for(CommunityPatrol communityPatrol:communityPatrols){
                communityPatrol.setReportTimeStr(sdf.format(communityPatrol.getReportTime()));
            }
        }
        try {

            HSSFWorkbook workbook1 = ExcelUtil.makeExcelHead("企业巡查表", 9);
            String[] secondTitles = {"问题类别","所属区县","所属乡镇","上报时间","巡查人员","联系方式","现存问题","污染源名称","污染源地址","问题类型","情况说明","处理结果"};
            HSSFWorkbook workbook2 = ExcelUtil.makeSecondHead(workbook1, secondTitles);

            // String[] beanProperty = {user.getDep().getDeptName(),"userName","userPrivName", "roleAuxiliaryName","online","sex","online","telNoDept","telNoDept","departmentPhone","email"};
            String[] beanProperty = {"prolemType","subCounty","subVillage","reportTimeStr","patrolUser","contact","existingProblem","pollutionName","pollutionLocation","problemType","situationDes","processResult"};

            HSSFWorkbook workbook = ExcelUtil.exportExcelData(workbook2, communityPatrols, beanProperty);
            ServletOutputStream out = response.getOutputStream();

            String filename = "企业巡查表.xls";
            filename = FileUtils.encodeDownloadFilename(filename,
                    request.getHeader("user-agent"));
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-disposition",
                    "attachment;filename=" + filename);
            workbook.write(out);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return  baseWrapper;
    }

}
